package com.borya.filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.log4j.Logger;

import com.borya.framework.annotation.Filter;
import com.borya.framework.constant.ContentTypes;
import com.borya.framework.core.ServerFilter;
import com.borya.framework.core.ServerRequest;
import com.borya.framework.core.ServerResponse;
import com.borya.framework.util.ObjectUtils;
import com.borya.util.Constant;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;

@Filter(-100)
public class StaticResourceAccessFilter implements ServerFilter {

	private Logger log = Logger.getLogger(getClass());

	private final String HTML_SUFFIX = ".html";
	private final String HTM_SUFFIX = ".htm";
	private final String CSS_SUFFIX = ".css";
	private final String PNG_SUFFIX = ".png";
	private final String JPG_SUFFIX = ".jpg";
	private final String JPEG_SUFFIX = ".jpeg";
	private final String ICO_SUFFIX = ".ico";
	private final String JS_SUFFIX = ".js";
	private final int BUFFER_SIZE = 4 * 1024;

	@Override
	public boolean doFilter(ServerRequest request, ServerResponse response) {
		final String path = request.path();
//		System.out.println(String.format("Receive path %s", path));
		if (ObjectUtils.isNullOrEmpty(path)) {
			return false;
		}
		try {
			if (path.endsWith(HTML_SUFFIX) || path.endsWith(HTM_SUFFIX)) {
				responseResource(path, response);
				response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.TEXT_HTML);
				return true;
			} else if (path.endsWith(CSS_SUFFIX)) {
				responseResource(path, response);
				response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.TEXT_CSS);
				return true;
			}  else if (path.endsWith(JS_SUFFIX)) {
				responseResource(path, response);
				response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.TEXT_CSS);
				return true;
			} else if (path.endsWith(ICO_SUFFIX)) {
				responseResource(path, response);
				response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.IMAGE_PNG);
				return true;
			} else if (path.endsWith(PNG_SUFFIX)) {
				if(path.contains("/sign/")){
					responseResource_Photo(path, response, "/sign/",
							Constant.IMG_SAVE_PATH, false);
				}else if(path.contains("/registing/")){
					responseResource_Photo(path, response, "/registing/",
							Constant.IMG_SAVE_PATH, false);;
				}else if(path.contains("/askpower/")){
					responseResource_Photo(path, response, "/askpower/",
							Constant.IMG_SAVE_PATH, false);
				}else{
					responseResource(path, response);
				}
				response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.IMAGE_PNG);
				return true;
			} else if (path.endsWith(JPG_SUFFIX) || path.endsWith(JPEG_SUFFIX)) {
				if(path.contains("/sign/")){
					responseResource_Photo(path, response, "/sign/",
							Constant.IMG_SAVE_PATH, false);
				}else if(path.contains("/registing/")){
					responseResource_Photo(path, response, "/registing/",
							Constant.IMG_SAVE_PATH, false);;
				}else if(path.contains("/askpower/")){
					responseResource_Photo(path, response, "/askpower/",
							Constant.IMG_SAVE_PATH, false);
				}else if(path.contains(Constant.SpecialTag.SHQP)){
					responseResource_Photo(path, response, Constant.SpecialTag.SHQP,
							Constant.IMG_SAVE_PATH, false);
				}else {
					responseResource(path, response);
				}
				response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.IMAGE_JPG);
				return true;
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
			response.content().clear()
					.writeBytes(HttpResponseStatus.INTERNAL_SERVER_ERROR.toString().getBytes(CharsetUtil.UTF_8));
			response.headers().add(HttpHeaderNames.CONTENT_TYPE, ContentTypes.TEXT_PLAIN);
			return true;
		}
		return false;
	}

	private void responseResource_Photo(String path_point, ServerResponse response,
			String specialPath, String rootPath,
			boolean cutStr) {
		if (path_point == null || path_point.isEmpty() || response == null) {
			return;
		}
		String pathAndFileName = "";
		if(cutStr){
			pathAndFileName = rootPath
					+ path_point.substring(path_point.lastIndexOf(specialPath)
							+specialPath.length());
		}else{
			pathAndFileName = rootPath
					+ path_point.substring(path_point.lastIndexOf(specialPath));
		}

		File file = new File(pathAndFileName);

		if(! file.exists()){
			return;
		}
		try (InputStream in = new FileInputStream(file)) {
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = -1;
			while ((len = in.read(buffer)) != -1) {
				response.content().writeBytes(buffer, 0, len);
			}
		} catch (Exception e) {
//			throw e;
			e.printStackTrace();
		}
	}


	private void responseResource(String path, ServerResponse response) throws Exception {
		if (path == null || path.isEmpty() || response == null) {
			return;
		}
		try (InputStream in = StaticResourceAccessFilter.class.getResourceAsStream(path)) {
			if(in == null){
				log.info("file not found,"+path);
				response.content().writeBytes(HttpResponseStatus.BAD_REQUEST.toString().getBytes(CharsetUtil.UTF_8));
				return;
			}
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = -1;
			while ((len = in.read(buffer)) != -1) {
				response.content().writeBytes(buffer, 0, len);
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw e;
		}
	}
//	public static void main(String[] args) {
//		String path = "/web/dist/card/index.html";
//		InputStream in = StaticResourceAccessFilter.class.getResourceAsStream(path);
//		
//		System.out.println(in);
//		
//	}
}
